#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>

/*
    About Linklist with nohead;
*/

typedef struct node{
    int data;
    struct node *next;
}Node, *Linklist;

//declare
void printLIst_sq(Linklist L);
void InsertBack(Linklist *L, int data);
void InsertFront(Linklist *L, int data);
void Init(Linklist *L);
void remove_nohead(Linklist *L, int data);
Node* _buyNode_nohead(int data);
void CreateList_nohead(Linklist *L, int n);

void Init(Linklist *L) {
    // (*L) = (Node*)malloc(sizeof(Node));
    (*L) = NULL;
    printf("list inited.\n");
}

Node* _buyNode_nohead(int data) {
    Node *p = (Node*)malloc(sizeof(Node));
    p->next = NULL;
    p->data = data;
    return p;
}

void CreateList_nohead(Linklist *L, int n) {
    Init(L);
    int data;
    printf("input %d data:\n", n);
    for(int i = 0; i < n; i++) {
        scanf("%d", &data);
        InsertBack(L, data);
    }
    printf("\ncreated.\n");
}

void InsertFront(Linklist *L, int data) {
    Node *p = _buyNode_nohead(data);
    assert(p);
    p->next = *L;
    *L = p;
}

void InsertBack(Linklist *L, int data) {
    Node *tail = *L;
    if(*L == NULL) {
        Node *p = _buyNode_nohead(data);
        *L = p;
        return;
    }
    while(tail->next != NULL) {
        tail = tail->next;
    }
    Node *p = _buyNode_nohead(data);
    assert(p);
    tail->next = p;
    p->next = NULL;
}

void remove_nohead(Linklist *L, int data) {
    Node *p = *L;
    if(data == p->data) {
        *L = p->next;
        return;
    }
    Node *q;
    while(p->next != NULL) {
        q = p->next;
        if(q->data == data) {
            p->next = q->next;
            q->next = NULL;
            free(q);
            return;
        }
        p = p->next;
    }
}

//printlist
void printLIst_sq(Linklist L) {
    Node *p = L;
    printf("list is below:\n");
    while(p != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

int main(int argc, char const *argv[])
{
    Linklist L;
    // Init(&L);
    int n;
    printf("input n:\n");
    scanf("%d", &n);
    CreateList_nohead(&L, n);
    // InsertBack(&L, 3);
    // InsertBack(&L, 4);
    // InsertBack(&L, 5);
    printLIst_sq(L);
    printf("now we insert front:\n");
    InsertFront(&L, 8);
    printLIst_sq(L);

    // remove_nohead(&L, 8);
    remove_nohead(&L, 3);
    printLIst_sq(L);
    return 0;
}
